package com.music.note_android.ui.editor

import android.graphics.*
import android.util.LruCache
import kotlin.math.max
import kotlin.math.min

/**
 * 绘制引擎
 * 负责实际的绘制操作、性能优化、硬件加速和渲染效果
 */
class DrawingEngine {
    
    // Paint对象池，避免频繁创建对象
    private val paintPool = mutableListOf<Paint>()
    private val pathPool = mutableListOf<Path>()
    
    // 不同工具的Paint缓存
    private val penPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
    }
    
    private val pencilPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
        // 铅笔效果：略微透明
        alpha = 230
    }
    
    private val highlighterPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
        // 荧光笔效果：半透明
        alpha = 128
    }
    
    private val eraserPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }
    
    // 路径缓存，用于优化重复绘制
    private val pathCache = LruCache<String, Path>(100)
    
    // 当前正在绘制的笔画
    private var currentStroke: Stroke? = null
    private var currentPath: Path? = null
    
    // 脏区域管理
    private val dirtyRegions = mutableListOf<RectF>()
    
    // 铅笔纹理（模拟真实铅笔效果）
    private var pencilTexture: Bitmap? = null
    
    /**
     * 初始化绘制引擎
     */
    fun initialize() {
        // 预创建一些Paint和Path对象
        repeat(10) {
            paintPool.add(createPaint())
            pathPool.add(Path())
        }
        
        // 创建铅笔纹理
        createPencilTexture()
    }
    
    /**
     * 创建铅笔纹理
     */
    private fun createPencilTexture() {
        // 创建一个小的纹理位图来模拟铅笔效果
        val textureSize = 32
        pencilTexture = Bitmap.createBitmap(textureSize, textureSize, Bitmap.Config.ALPHA_8)
        val canvas = Canvas(pencilTexture!!)
        val paint = Paint().apply {
            isAntiAlias = false
            color = Color.BLACK
        }
        
        // 绘制随机点来模拟铅笔纹理
        for (i in 0 until textureSize * textureSize / 4) {
            val x = (Math.random() * textureSize).toFloat()
            val y = (Math.random() * textureSize).toFloat()
            val alpha = (Math.random() * 100 + 50).toInt()
            paint.alpha = alpha
            canvas.drawPoint(x, y, paint)
        }
    }
    
    /**
     * 渲染画布内容
     */
    fun render(canvas: Canvas, visibleBounds: RectF) {
        // 设置裁剪区域以提高性能
        canvas.clipRect(visibleBounds)
        
        // 绘制背景网格（可选）
        drawGrid(canvas, visibleBounds)
        
        // 绘制所有笔画
        renderStrokes(canvas, visibleBounds)
        
        // 绘制当前正在绘制的笔画
        currentStroke?.let { stroke ->
            renderStroke(canvas, stroke)
        }
    }
    
    /**
     * 渲染画布内容（完整版本）
     */
    fun renderCanvas(
        canvas: Canvas,
        canvasManager: CanvasManager,
        viewWidth: Int,
        viewHeight: Int,
        offsetX: Float,
        offsetY: Float,
        scale: Float
    ) {
        // 保存画布状态
        canvas.save()
        
        try {
            // 应用变换矩阵
            canvas.translate(offsetX, offsetY)
            canvas.scale(scale, scale)
            
            // 计算可见区域
            val viewBounds = calculateViewBounds(viewWidth, viewHeight, offsetX, offsetY, scale)
            
            // 绘制背景网格
            if (showGrid) {
                drawGrid(canvas, viewBounds, scale)
            }
            
            // 获取可见笔画
            val visibleStrokes = canvasManager.getVisibleStrokes(viewBounds)
            
            // 渲染笔画
            renderStrokes(canvas, visibleStrokes, scale)
            
            // 渲染当前正在绘制的笔画（实时绘画）
            currentStroke?.let { stroke ->
                renderStroke(canvas, stroke, scale)
            }
            
            // 更新性能统计
            updatePerformanceStats(visibleStrokes.size)
            
        } finally {
            // 恢复画布状态
            canvas.restore()
        }
    }
    
    // 网格显示开关
    private var showGrid = false
    
    // 网格画笔
    private val gridPaint = Paint().apply {
        color = Color.LTGRAY
        strokeWidth = 1f
        alpha = 50
    }
    
    /**
     * 绘制背景网格
     */
    private fun drawGrid(canvas: Canvas, bounds: RectF) {
        // 网格线间距
        val gridSize = 50f
        
        val gridPaint = Paint().apply {
            color = Color.LTGRAY
            strokeWidth = 1f
            alpha = 50
        }
        
        // 绘制垂直线
        var x = (bounds.left / gridSize).toInt() * gridSize
        while (x <= bounds.right) {
            canvas.drawLine(x, bounds.top, x, bounds.bottom, gridPaint)
            x += gridSize
        }
        
        // 绘制水平线
        var y = (bounds.top / gridSize).toInt() * gridSize
        while (y <= bounds.bottom) {
            canvas.drawLine(bounds.left, y, bounds.right, y, gridPaint)
            y += gridSize
        }
    }
    
    /**
     * 绘制背景网格（带缩放）
     */
    private fun drawGrid(canvas: Canvas, bounds: RectF, scale: Float) {
        // 根据缩放级别调整网格密度
        val gridSpacing = when {
            scale > 2.0f -> 20f
            scale > 1.0f -> 50f
            scale > 0.5f -> 100f
            else -> 200f
        }
        
        // 设置网格画笔
        gridPaint.alpha = (128 * scale.coerceIn(0.1f, 1.0f)).toInt()
        
        // 计算网格起始位置
        val startX = (bounds.left / gridSpacing).toInt() * gridSpacing
        val startY = (bounds.top / gridSpacing).toInt() * gridSpacing
        
        // 绘制垂直线
        var x = startX
        while (x <= bounds.right) {
            canvas.drawLine(x, bounds.top, x, bounds.bottom, gridPaint)
            x += gridSpacing
        }
        
        // 绘制水平线
        var y = startY
        while (y <= bounds.bottom) {
            canvas.drawLine(bounds.left, y, bounds.right, y, gridPaint)
            y += gridSpacing
        }
    }
    
    // 笔画画笔
    private val strokePaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
    }
    
    /**
     * 渲染多个笔画
     */
    private fun renderStrokes(canvas: Canvas, visibleBounds: RectF) {
        // 这里应该从CanvasManager获取可见区域内的笔画
        // 为了简化，这里暂时留空，实际使用时需要传入笔画列表
    }
    
    /**
     * 渲染笔画（带缩放）
     */
    private fun renderStrokes(canvas: Canvas, strokes: List<Stroke>, scale: Float) {
        strokes.forEach { stroke ->
            renderStroke(canvas, stroke, scale)
        }
    }
    
    /**
     * 渲染单个笔画（带缩放）
     */
    private fun renderStroke(canvas: Canvas, stroke: Stroke, scale: Float) {
        if (stroke.points.isEmpty()) return
        
        // 构建笔画路径
        val path = buildStrokePath(stroke)
        
        // 配置画笔
        configurePaint(stroke, scale)
        
        // 绘制笔画
        when (stroke.tool) {
            DrawingTool.PEN -> {
                canvas.drawPath(path, strokePaint)
            }
            DrawingTool.PENCIL -> {
                // 铅笔效果：稍微透明
                strokePaint.alpha = (255 * 0.8f).toInt()
                canvas.drawPath(path, strokePaint)
            }
            DrawingTool.HIGHLIGHTER -> {
                // 荧光笔效果：高透明度
                strokePaint.alpha = (255 * stroke.alpha).toInt()
                canvas.drawPath(path, strokePaint)
            }
            DrawingTool.ERASER -> {
                // 橡皮擦不在这里渲染
            }
        }
    }
    
    /**
     * 渲染单个笔画
     */
    fun renderStroke(canvas: Canvas, stroke: Stroke) {
        if (stroke.points.isEmpty()) return
        
        val paint = getPaintForTool(stroke.tool)
        configurePaint(paint, stroke)
        
        when (stroke.tool) {
            DrawingTool.PEN -> renderPenStroke(canvas, stroke, paint)
            DrawingTool.PENCIL -> renderPencilStroke(canvas, stroke, paint)
            DrawingTool.HIGHLIGHTER -> renderHighlighterStroke(canvas, stroke, paint)
            DrawingTool.ERASER -> renderEraserStroke(canvas, stroke, paint)
        }
    }
    
    /**
     * 渲染钢笔笔画
     */
    private fun renderPenStroke(canvas: Canvas, stroke: Stroke, paint: Paint) {
        val path = getOrCreatePath(stroke)
        canvas.drawPath(path, paint)
    }
    
    /**
     * 渲染铅笔笔画
     */
    private fun renderPencilStroke(canvas: Canvas, stroke: Stroke, paint: Paint) {
        // 铅笔效果：使用纹理和略微的透明度
        val path = getOrCreatePath(stroke)
        
        // 先绘制基础路径
        canvas.drawPath(path, paint)
        
        // 如果有纹理，叠加纹理效果
        pencilTexture?.let { texture ->
            val texturePaint = Paint().apply {
                shader = BitmapShader(texture, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
                alpha = 50
                xfermode = PorterDuffXfermode(PorterDuff.Mode.MULTIPLY)
            }
            canvas.drawPath(path, texturePaint)
        }
    }
    
    /**
     * 渲染荧光笔笔画
     */
    private fun renderHighlighterStroke(canvas: Canvas, stroke: Stroke, paint: Paint) {
        // 荧光笔效果：半透明，较粗的线条
        val path = getOrCreatePath(stroke)
        canvas.drawPath(path, paint)
    }
    
    /**
     * 渲染橡皮擦笔画
     */
    private fun renderEraserStroke(canvas: Canvas, stroke: Stroke, paint: Paint) {
        val path = getOrCreatePath(stroke)
        canvas.drawPath(path, paint)
    }
    
    /**
     * 获取或创建笔画路径
     */
    private fun getOrCreatePath(stroke: Stroke): Path {
        // 尝试从缓存获取
        pathCache.get(stroke.id)?.let { return it }
        
        // 创建新路径
        val path = getPathFromPool()
        buildStrokePath(path, stroke)
        
        // 缓存路径
        pathCache.put(stroke.id, path)
        
        return path
    }
    
    /**
     * 构建笔画路径（新版本）
     */
    private fun buildStrokePath(stroke: Stroke): Path {
        val path = getPathFromPool()
        path.reset()
        
        if (stroke.points.isEmpty()) return path
        
        val points = stroke.points
        
        if (points.size == 1) {
            // 单点绘制为小圆
            val point = points[0]
            val radius = stroke.width * point.pressure.coerceIn(0.3f, 1.0f) / 2f
            path.addCircle(point.x, point.y, radius, Path.Direction.CW)
        } else {
            // 根据工具类型选择不同的路径构建方式
            when (stroke.tool) {
                DrawingTool.PEN -> buildSmoothPath(path, points, stroke)
                DrawingTool.PENCIL -> buildTexturedPath(path, points, stroke)
                DrawingTool.HIGHLIGHTER -> buildHighlighterPath(path, points, stroke)
                DrawingTool.ERASER -> buildSmoothPath(path, points, stroke)
            }
        }
        
        return path
    }
    
    /**
     * 构建纹理路径（用于铅笔）
     */
    private fun buildTexturedPath(path: Path, points: List<StrokePoint>, stroke: Stroke) {
        if (points.size < 2) return
        
        path.moveTo(points[0].x, points[0].y)
        
        for (i in 1 until points.size) {
            val prevPoint = points[i - 1]
            val currentPoint = points[i]
            
            // 根据压感和速度添加抖动
            val pressure = currentPoint.pressure
            val speed = if (i > 0) {
                val distance = kotlin.math.sqrt(
                    (currentPoint.x - prevPoint.x) * (currentPoint.x - prevPoint.x) +
                    (currentPoint.y - prevPoint.y) * (currentPoint.y - prevPoint.y)
                )
                val time = (currentPoint.timestamp - prevPoint.timestamp).coerceAtLeast(1)
                distance / time
            } else 0f
            
            // 低压感或高速度时添加抖动效果
            val jitterAmount = (1.0f - pressure) * 0.5f + speed * 0.1f
            val jitterX = (Math.random().toFloat() - 0.5f) * jitterAmount
            val jitterY = (Math.random().toFloat() - 0.5f) * jitterAmount
            
            val targetX = currentPoint.x + jitterX
            val targetY = currentPoint.y + jitterY
            
            // 使用二次贝塞尔曲线连接
            val midX = (prevPoint.x + targetX) / 2
            val midY = (prevPoint.y + targetY) / 2
            path.quadTo(prevPoint.x, prevPoint.y, midX, midY)
        }
    }
    
    /**
     * 构建荧光笔路径
     */
    private fun buildHighlighterPath(path: Path, points: List<StrokePoint>, stroke: Stroke) {
        if (points.size < 2) return
        
        // 荧光笔使用较粗的直线连接，模拟扁平笔尖
        path.moveTo(points[0].x, points[0].y)
        
        for (i in 1 until points.size) {
            val currentPoint = points[i]
            path.lineTo(currentPoint.x, currentPoint.y)
        }
    }
    
    /**
     * 构建平滑路径
     */
    private fun buildSmoothPath(path: Path, points: List<StrokePoint>, stroke: Stroke) {
        if (points.size < 2) return
        
        // 移动到起始点
        path.moveTo(points[0].x, points[0].y)
        
        if (points.size == 2) {
            // 两点直接连线
            path.lineTo(points[1].x, points[1].y)
        } else {
            // 使用贝塞尔曲线平滑连接
            for (i in 1 until points.size - 1) {
                val current = points[i]
                val next = points[i + 1]
                
                // 计算控制点
                val controlX = (current.x + next.x) / 2f
                val controlY = (current.y + next.y) / 2f
                
                path.quadTo(current.x, current.y, controlX, controlY)
            }
            
            // 连接到最后一点
            val lastPoint = points.last()
            path.lineTo(lastPoint.x, lastPoint.y)
        }
    }
    
    /**
     * 构建笔画路径
     */
    private fun buildStrokePath(path: Path, stroke: Stroke) {
        path.reset()
        
        if (stroke.points.isEmpty()) return
        
        if (stroke.points.size == 1) {
            // 单点：绘制圆点
            val point = stroke.points[0]
            val radius = getStrokeWidth(stroke, point) / 2f
            path.addCircle(point.x, point.y, radius, Path.Direction.CW)
            return
        }
        
        // 多点：构建平滑路径
        if (stroke.tool.supportsPressure()) {
            buildPressureSensitivePath(path, stroke)
        } else {
            buildSimplePath(path, stroke)
        }
    }
    
    /**
     * 构建压感敏感路径
     */
    private fun buildPressureSensitivePath(path: Path, stroke: Stroke) {
        val points = stroke.points
        if (points.size < 2) return
        
        // 使用贝塞尔曲线创建平滑路径
        path.moveTo(points[0].x, points[0].y)
        
        for (i in 1 until points.size) {
            val prev = points[i - 1]
            val curr = points[i]
            
            if (i == 1) {
                // 第一段：直线到第二个点
                path.lineTo(curr.x, curr.y)
            } else {
                // 后续段：使用二次贝塞尔曲线
                val next = if (i < points.size - 1) points[i + 1] else curr
                val controlX = (prev.x + curr.x) / 2f
                val controlY = (prev.y + curr.y) / 2f
                path.quadTo(controlX, controlY, curr.x, curr.y)
            }
        }
    }
    
    /**
     * 构建简单路径
     */
    private fun buildSimplePath(path: Path, stroke: Stroke) {
        val points = stroke.points
        if (points.isEmpty()) return
        
        path.moveTo(points[0].x, points[0].y)
        
        for (i in 1 until points.size) {
            path.lineTo(points[i].x, points[i].y)
        }
    }
    
    /**
     * 获取工具对应的Paint对象
     */
    private fun getPaintForTool(tool: DrawingTool): Paint {
        return when (tool) {
            DrawingTool.PEN -> penPaint
            DrawingTool.PENCIL -> pencilPaint
            DrawingTool.HIGHLIGHTER -> highlighterPaint
            DrawingTool.ERASER -> eraserPaint
        }
    }
    
    /**
     * 配置Paint对象
     */
    private fun configurePaint(paint: Paint, stroke: Stroke) {
        // 重置画笔状态
        paint.reset()
        paint.isAntiAlias = true
        
        paint.color = stroke.color
        paint.strokeWidth = stroke.width
        paint.alpha = (stroke.alpha * 255).toInt()
        
        when (stroke.tool) {
            DrawingTool.PEN -> {
                configurePenPaint(paint, stroke)
            }
            DrawingTool.PENCIL -> {
                configurePencilPaint(paint, stroke)
            }
            DrawingTool.HIGHLIGHTER -> {
                configureHighlighterPaint(paint, stroke)
            }
            DrawingTool.ERASER -> {
                configureEraserPaint(paint, stroke)
            }
        }
    }
    
    /**
     * 配置钢笔画笔
     */
    private fun configurePenPaint(paint: Paint, stroke: Stroke) {
        paint.style = Paint.Style.STROKE
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeJoin = Paint.Join.ROUND
        paint.isAntiAlias = true
        
        // 钢笔具有最佳的平滑度和精确度
        paint.pathEffect = null
        paint.maskFilter = null
        
        // 支持压感变化
        if (stroke.points.isNotEmpty()) {
            val avgPressure = stroke.points.map { it.pressure }.average().toFloat()
            val pressureAlpha = (0.8f + 0.2f * avgPressure).coerceIn(0.5f, 1.0f)
            paint.alpha = (paint.alpha * pressureAlpha).toInt()
        }
    }
    
    /**
     * 配置铅笔画笔
     */
    private fun configurePencilPaint(paint: Paint, stroke: Stroke) {
        paint.style = Paint.Style.STROKE
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeJoin = Paint.Join.ROUND
        paint.isAntiAlias = true
        
        // 铅笔具有纹理效果
        paint.alpha = (paint.alpha * 0.7f).toInt()
        
        // 添加轻微的模糊效果模拟铅笔纹理
        paint.maskFilter = BlurMaskFilter(0.5f, BlurMaskFilter.Blur.NORMAL)
        
        // 支持压感，影响透明度和宽度
        if (stroke.points.isNotEmpty()) {
            val avgPressure = stroke.points.map { it.pressure }.average().toFloat()
            val pressureAlpha = (0.4f + 0.6f * avgPressure).coerceIn(0.3f, 0.9f)
            paint.alpha = (paint.alpha * pressureAlpha).toInt()
            
            // 压感影响笔触粗糙度
            if (avgPressure < 0.3f) {
                // 轻压时添加虚线效果
                val intervals = floatArrayOf(stroke.width * 0.5f, stroke.width * 0.2f)
                paint.pathEffect = DashPathEffect(intervals, 0f)
            }
        }
    }
    
    /**
     * 配置荧光笔画笔
     */
    private fun configureHighlighterPaint(paint: Paint, stroke: Stroke) {
        paint.style = Paint.Style.STROKE
        paint.strokeCap = Paint.Cap.SQUARE
        paint.strokeJoin = Paint.Join.MITER
        paint.isAntiAlias = false // 荧光笔边缘较硬
        
        // 荧光笔具有半透明效果
        paint.alpha = (paint.alpha * 0.4f).toInt()
        
        // 使用叠加混合模式模拟荧光效果
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.MULTIPLY)
        
        // 荧光笔宽度通常较大
        paint.strokeWidth = Math.max(stroke.width, 8f)
        
        // 添加发光效果
        paint.setShadowLayer(3f, 0f, 0f, stroke.color)
    }
    
    /**
     * 配置橡皮擦画笔
     */
    private fun configureEraserPaint(paint: Paint, stroke: Stroke) {
        paint.style = Paint.Style.STROKE
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeJoin = Paint.Join.ROUND
        paint.isAntiAlias = true
        
        // 橡皮擦使用清除模式
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        
        // 橡皮擦不需要颜色和透明度
        paint.color = Color.TRANSPARENT
        paint.alpha = 255
    }
    
    /**
     * 配置画笔（带缩放）
     */
    private fun configurePaint(stroke: Stroke, scale: Float) {
        strokePaint.apply {
            color = stroke.color
            strokeWidth = stroke.width * scale
            alpha = (255 * stroke.alpha).toInt()
            
            // 根据工具类型设置画笔属性
            when (stroke.tool) {
                DrawingTool.PEN -> {
                    style = Paint.Style.STROKE
                    strokeCap = Paint.Cap.ROUND
                    strokeJoin = Paint.Join.ROUND
                    pathEffect = null
                }
                DrawingTool.PENCIL -> {
                    style = Paint.Style.STROKE
                    strokeCap = Paint.Cap.ROUND
                    strokeJoin = Paint.Join.ROUND
                    // 可以添加纹理效果
                    pathEffect = null
                }
                DrawingTool.HIGHLIGHTER -> {
                    style = Paint.Style.STROKE
                    strokeCap = Paint.Cap.SQUARE
                    strokeJoin = Paint.Join.MITER
                    pathEffect = null
                }
                DrawingTool.ERASER -> {
                    // 橡皮擦使用特殊模式
                    xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
                }
            }
        }
    }
    
    /**
     * 计算考虑压感的笔画粗细
     */
    private fun getStrokeWidth(stroke: Stroke, point: StrokePoint): Float {
        if (!stroke.tool.supportsPressure()) {
            return stroke.width
        }
        
        // 压感影响范围：50%-200%
        val pressureMultiplier = 0.5f + point.pressure * 1.5f
        return stroke.width * pressureMultiplier
    }
    
    /**
     * 开始新笔画
     */
    fun startStroke(stroke: Stroke) {
        currentStroke = stroke
        currentPath = getPathFromPool()
        
        // 添加脏区域
        addDirtyRegion(stroke.getBounds())
    }
    
    /**
     * 更新当前笔画
     */
    fun updateStroke(stroke: Stroke) {
        currentStroke = stroke
        currentPath?.let { path ->
            buildStrokePath(path, stroke)
        }
        
        // 更新脏区域
        addDirtyRegion(stroke.getBounds())
    }
    
    /**
     * 完成当前笔画
     */
    fun finishStroke(stroke: Stroke) {
        currentPath?.let { path ->
            // 将路径添加到缓存
            pathCache.put(stroke.id, path)
        }
        
        currentStroke = null
        currentPath = null
        
        // 最终更新脏区域
        addDirtyRegion(stroke.getBounds())
    }
    
    /**
     * 添加脏区域
     */
    private fun addDirtyRegion(bounds: RectF) {
        dirtyRegions.add(RectF(bounds))
        
        // 限制脏区域数量
        if (dirtyRegions.size > 50) {
            dirtyRegions.removeFirstOrNull()
        }
    }
    
    /**
     * 获取脏区域
     */
    fun getDirtyRegions(): List<RectF> {
        return dirtyRegions.toList()
    }
    
    /**
     * 清空脏区域
     */
    fun clearDirtyRegions() {
        dirtyRegions.clear()
    }
    
    /**
     * 从对象池获取Paint
     */
    private fun getPaintFromPool(): Paint {
        return if (paintPool.isNotEmpty()) {
            paintPool.removeLastOrNull() ?: createPaint()
        } else {
            createPaint()
        }
    }
    
    /**
     * 从对象池获取Path
     */
    private fun getPathFromPool(): Path {
        return if (pathPool.isNotEmpty()) {
            val path = pathPool.removeLastOrNull() ?: Path()
            path.reset()
            path
        } else {
            Path()
        }
    }
    
    /**
     * 将Paint返回对象池
     */
    private fun returnPaintToPool(paint: Paint) {
        if (paintPool.size < 20) {
            paint.reset()
            paintPool.add(paint)
        }
    }
    
    /**
     * 将Path返回对象池
     */
    private fun returnPathToPool(path: Path) {
        if (pathPool.size < 20) {
            path.reset()
            pathPool.add(path)
        }
    }
    
    /**
     * 创建新的Paint对象
     */
    private fun createPaint(): Paint {
        return Paint().apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            strokeCap = Paint.Cap.ROUND
            strokeJoin = Paint.Join.ROUND
        }
    }
    
    /**
     * 清空绘制引擎
     */
    fun clear() {
        pathCache.evictAll()
        dirtyRegions.clear()
        currentStroke = null
        currentPath = null
    }
    
    /**
     * 计算可见区域
     */
    private fun calculateViewBounds(
        viewWidth: Int,
        viewHeight: Int,
        offsetX: Float,
        offsetY: Float,
        scale: Float
    ): RectF {
        // 计算画布坐标系中的可见区域
        val left = -offsetX / scale
        val top = -offsetY / scale
        val right = left + viewWidth / scale
        val bottom = top + viewHeight / scale
        
        return RectF(left, top, right, bottom)
    }
    
    /**
     * 更新性能统计
     */
    private fun updatePerformanceStats(strokeCount: Int) {
        // TODO: 实现性能统计更新
    }
    
    /**
     * 获取绘制引擎统计信息
     */
    fun getStatistics(): DrawingEngineStatistics {
        return DrawingEngineStatistics(
            pathCacheSize = pathCache.size(),
            paintPoolSize = paintPool.size,
            pathPoolSize = pathPool.size,
            dirtyRegionCount = dirtyRegions.size
        )
    }
    
    /**
     * 绘制引擎统计信息
     */
    data class DrawingEngineStatistics(
        val pathCacheSize: Int,
        val paintPoolSize: Int,
        val pathPoolSize: Int,
        val dirtyRegionCount: Int
    )
}